package edu.biwu.dao.impl;

import edu.biwu.dao.ProductDao;
import edu.biwu.mapper.ProductMapper;
import edu.biwu.po.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author 王俊彪
 * @version 1.0
 */
@Repository("productDaoImpl1")
public class ProductDaoImpl implements ProductDao {

    /*将来交给spring 去注入*/
//    @Resource
//    private QueryRunner queryRunner;

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public void saveProduct(Product product) {
        jdbcTemplate.update("INSERT INTO spring.product (pname, price, category) VALUES (?,?,?)"
                ,product.getPname(),product.getPrice(),product.getCategory());

    }

    @Override
    public void updateProduct(Product product) {
//        try {
//            queryRunner.update("UPDATE spring.product SET pname=?,price=?,category=? WHERE " +
//                    " pid = ?",product.getPname(),product.getPrice(),product.getCategory(),product.getPid());
//
//        } catch (SQLException e) {
//            throw new RuntimeException(e.getMessage());
//        }
        jdbcTemplate.update("UPDATE spring.product SET price = ? ,pname=?,category=? WHERE pid=?",product.getPrice(),product.getPname(),product.getCategory(),product.getPid());
        int i = 1/0;
    }

    @Override
    public void deleteProductById(int id) {
        jdbcTemplate.update("DELETE FROM spring.product WHERE pid = ?" , id);

    }

    @Override
    public List<Product> findAll() {
//        try {
//            return queryRunner.query("SELECT * FROM spring.product",
//                    new BeanListHandler<Product>(Product.class));
//        } catch (SQLException e) {
//            throw new RuntimeException(e.getMessage());
//        }
        return jdbcTemplate.query("SELECT * FROM spring.product",productMapper);

    }

    @Override
    public Product findById(int id) {
        return jdbcTemplate.queryForObject("SELECT * FROM spring.product WHERE pid = ?"
                , productMapper,id);
    }

//    public ProductDaoImpl(QueryRunner queryRunner) {
//        this.queryRunner = queryRunner;
//    }

    public ProductDaoImpl() {
    }

//    public void setQueryRunner(QueryRunner queryRunner) {
//        this.queryRunner = queryRunner;
//    }
}
